﻿package pl.krasi.game 
{
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLRequest;
	
	import gs.*;
	import gs.easing.*;
	
	/**
	 * ...
	 * @author Mblaszczyk
	 */
	public class Display extends Sprite
	{
		
		private var _picData:Array
		private var _displayInfo:Array;
		private var _counter:Number = 0;
		public var loaderArray:Array = new Array();
		public var minisList:Array;
		
		public function Display(a:Array) 
		{
			trace("Display startup");
			trace(a.length);
			
			_picData = new Array();
			for (var j:int = 0; j < a.length; j++) {
				_picData[j] = new Array();
				_picData[j]['name'] = a[j]['name'];
				_picData[j]['pic_square'] = a[j]['pic_square'];
			}
			
			trace ("tablica _picData ready");
			
			_displayInfo = new Array();
			minisList = new Array();
			for (j = 0; j < 25; j++) {
				minisList[j] = new Array();
			}
			
			//Fill array containing "blocks" of our bg.
			for (var i:int = 0; i < 25 * 16; i++) {
				_displayInfo[i] = new Array();
				_displayInfo[i] = _picData[i % _picData.length];
			}
			
			trace ("utworzono _displayInfo o dlugosci: ", _displayInfo.length);
			
			//it will be nice to add some random to stage - permutation
			for (i = 0; i < _displayInfo.length; i++) {
				var n:Number = Math.floor(Math.random() * _displayInfo.length);
				
				var tmp:Array = _displayInfo[i];
				_displayInfo[i] = _displayInfo[n];
				_displayInfo[n] = tmp;
				
			}
			//this should do the trick:)
			imageLoader();
		}
		
		private function imageLoader(): void {
			trace ("tick imageLoadera. ", _counter, " / ", _displayInfo.length);
			if (_counter < _displayInfo.length ) {
				var loader:Loader = new Loader();
				addChild(loader);
				loaderArray.push(loader);
			
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageComplete);
				loader.load(new URLRequest(_displayInfo[_counter]['pic_square'])); 
			} else {
				trace ("pobrano i umieszczono na scenie juz wszystkie obrazki");
				dispatchEvent(new Event(Event.COMPLETE));
			}

		}
		
		private function onImageComplete(e:Event) : void {
			trace("complete handler");
			var ldr:Loader = loaderArray[loaderArray.length - 1];
			
			TweenMax.to(ldr, 1, {colorMatrixFilter:{colorize:0x99CCFF}});
			
			ldr.x = (_counter % 25) * 30;
			ldr.y = Math.floor(_counter / 25 ) * 30;
			
			minisList[_counter % 25][Math.floor(_counter / 25 )] = ldr;
			
			ldr.width = 30;
			ldr.height = 30;
			_counter++;
			imageLoader();
		}
		
	}
	
}